package org.shagin.jfin.data.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.shagin.jfin.core.CoreUtils;

/**
 * The Class OperationCategory.
 */
public class OperationCategory extends AbstractBudgetItem {

    private OperationCategory parent = null;
    private List<OperationCategory> childs = new LinkedList<OperationCategory>();

    /**
     * Instantiates a new operation category.
     * 
     * @param parent the parent
     * @param name the name
     * @param budget the budget
     */
    public OperationCategory(OperationCategory parent, String name,
            IBudget budget) {
        this(name, budget);
        this.parent = parent;
    }

    /**
     * Instantiates a new operation category.
     * 
     * @param name the name
     * @param budget the budget
     */
    public OperationCategory(String name, IBudget budget) {
        super(name);
        CoreUtils.checkNotNull(budget, "budget");
        this.budget = budget;
    }

    /**
     * Gets the parent.
     * 
     * @return the parent
     */
    public OperationCategory getParent() {
        return parent;
    }

    /**
     * Adds the.
     * 
     * @param child the child
     */
    public void add(OperationCategory child) {
        child.parent = this;
        childs.add(child);
    }

    /**
     * Checks if is root.
     * 
     * @return true, if is root
     */
    public boolean isRoot() {
        return (null == parent);
    }

    /**
     * Gets the root.
     * 
     * @return the root
     */
    public OperationCategory getRoot() {
        OperationCategory result = this;
        while (!result.isRoot())
            result = result.getParent();
        return result;
    }

    /**
     * Gets the path.
     * 
     * @param divider the divider
     * @return the path
     */
    public String getPath(String divider) {
        List<String> list = new ArrayList<String>();
        list.add(getId());
        OperationCategory c = this;
        while (!c.isRoot()) {
            c = c.getParent();
            list.add(c.getId());
        }

        Collections.reverse(list);
        String result = "";
        for (String item : list)
            result += divider + item;

        return result;
    }

    /**
     * Gets the childs.
     * 
     * @return the childs
     */
    public List<OperationCategory> getChilds() {
        return childs;
    }

    /**
     * Gets the level.
     * 
     * @return the level
     */
    public int getLevel() {
        int result = 0;
        OperationCategory c = this;
        while (!c.isRoot()) {
            c = c.getParent();
            result++;
        }
        return result;
    }

    public IBudget getBudget() {
        return budget;
    }
}
